package com.xique.park.service.biz.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.xique.common.core.utils.DateUtils;
import com.xique.common.core.utils.OrikaUtil;
import com.xique.common.core.utils.SecurityUtils;
import com.xique.common.core.web.domain.AjaxResult;
import com.xique.park.api.IParkXiquePayCommandApi;
import com.xique.park.bean.domain.ParkDeviceNew;
import com.xique.park.bean.domain.ParkOn;
import com.xique.park.bean.domain.ParkUnlicensedCar;
import com.xique.park.bean.request.h5.noPlate.UnlicensedCarAdmissionRequest;
import com.xique.park.bean.request.h5.noPlate.UnlicensedCarGetPlateRequest;
import com.xique.park.bean.search.h5.ParkUnlicensedCarListSearch;
import com.xique.park.command.handler.UnlicensedCarInHandler;
import com.xique.park.constant.CommandConstant;
import com.xique.park.constant.CommandStatus;
import com.xique.park.constant.DictConstant;
import com.xique.park.constant.ResultCode;
import com.xique.park.constant.message.MessageConstants;
import com.xique.park.service.biz.service.IParkUnlicensedCarBizService;
import com.xique.park.service.service.IParkDeviceNewService;
import com.xique.park.service.service.IParkOnService;
import com.xique.park.service.service.IParkUnlicensedCarService;
import com.xique.park.utils.ParkCarUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * The type Park unlicensed car biz service.
 *
 * @author shd
 * @create 2022 /6/29 11:23
 */
@Service
@RequiredArgsConstructor
public class ParkUnlicensedCarBizServiceImpl implements IParkUnlicensedCarBizService {

    private final IParkUnlicensedCarService unlicensedCarService;

    private final IParkXiquePayCommandApi xiquePayCommandApi;

    private final UnlicensedCarInHandler unlicensedCarInHandler;

    private final IParkDeviceNewService parkDeviceNewService;

    private final IParkOnService parkOnService;

    @Override
    public AjaxResult getPlate(UnlicensedCarGetPlateRequest request) {
        Map<String, Object> map = new HashMap<>(2);
        ParkUnlicensedCarListSearch search = new ParkUnlicensedCarListSearch();
        search.setBaseUserId(SecurityUtils.getBaseUserId());
        List<ParkUnlicensedCar> list = unlicensedCarService.list(search);
        if (!list.isEmpty()) {
            List<ParkOn> parkOnList = parkOnService.selectParkOnByPlate(request.getParkId(),  list.get(0).getPlate());
            map.put("plate", list.get(0).getPlate());
            if (!parkOnList.isEmpty()){
                map.put("is_exist", true);
                return AjaxResult.success("成功", map);
            }
            map.put("is_exist", false);
            return AjaxResult.success("成功", map);
        }
        String plate = ParkCarUtil.getNoPlate();
        map.put("plate", plate);
        map.put("is_exist", false);
        return AjaxResult.success("成功", map);
    }

    @Override
    public AjaxResult admission(UnlicensedCarAdmissionRequest request) {
        ParkUnlicensedCarListSearch search = OrikaUtil.convert(request, ParkUnlicensedCarListSearch.class);
        List<ParkUnlicensedCar> list = unlicensedCarService.list(search);
        if (CollectionUtil.isEmpty(list)) {
            ParkUnlicensedCar unlicensedCar = OrikaUtil.convert(request, ParkUnlicensedCar.class);
            unlicensedCar.setCreateTime(DateUtils.getNowDate());
            unlicensedCar.setUpdateTime(DateUtils.getNowDate());
            unlicensedCar.setBaseUserId(SecurityUtils.getBaseUserId());
            boolean isSuccess = unlicensedCarService.save(unlicensedCar);
            if (!isSuccess) {
                return AjaxResult.error();
            }
        }

        unlicensedCarInHandler.setPlate(request.getPlate());
        String parkingSerial = DateUtils.parseDateToStr(DateUtils.YYYYMMDDHHMMSSSSS, DateUtils.getNowDate()) + "-" + request.getParkId() + request.getLaneId();
        unlicensedCarInHandler.setParkingSerial(parkingSerial);

        ParkDeviceNew parkDeviceNew = new ParkDeviceNew();
        parkDeviceNew.setIsMain(DictConstant.YES);
        parkDeviceNew.setLaneId(request.getLaneId());
        parkDeviceNew.setStatus(DictConstant.STATUS_NORMAL);
        parkDeviceNew.setRecordStatus(DictConstant.STATUS_NORMAL);
        List<ParkDeviceNew> devList = parkDeviceNewService.selectParkDeviceNewList(parkDeviceNew);
        if (CollectionUtil.isEmpty(devList)) {
            return AjaxResult.error("未找到对应的设备");
        }
        ParkDeviceNew deviceNew = devList.get(0);
        String message= "";
        String resultCode= "";
        AjaxResult commandResult = unlicensedCarInHandler.issue(request.getParkId(), deviceNew.getCode(), CommandConstant.MARK_UNLICENSED_CAR_IN);
        JSONObject jsonObject = JSONObject.parseObject((String) commandResult.get("data"));
        if (CommandStatus.SUCCESS.equals(jsonObject.getString("status"))) {
            // 如果应答成功了，则去查应答内容的是否有车
            int isCar = jsonObject.getJSONObject(MessageConstants.KEY_DT).getInteger("is_sensing_car");
            if (1 == isCar) {
                resultCode = ResultCode.OK;
                message = "无牌车成功入场";
            } else if (0 == isCar) {
                message = "当前通道未检测到车辆";
                resultCode = ResultCode.INTERNAL_ERROR;
            } else {
                message = "设备应答内容错误（是否有车：" + isCar + "）";
                resultCode = ResultCode.INTERNAL_ERROR;
            }
        } else {
            message = "设备未响应，请重试或联系车场！";
            resultCode = ResultCode.INTERNAL_ERROR;
        }

        return ResultCode.OK.equals(resultCode) ? AjaxResult.success(message) : AjaxResult.error(message);
    }
}
